import { resolve } from 'node:path'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'

/* unocss引入 */
import autoprefixer from 'autoprefixer'

/* 打包分析插件 */
import { visualizer } from 'rollup-plugin-visualizer'

import { createVitePlugins } from './build'
import { exclude, include } from './build/optimize'

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env: any = loadEnv(mode, process.cwd())

  return {
    base: env.VITE_BASE_PATH,
    server: {
      open: true,
      host: '0.0.0.0',
      port: 4600,
      hmr: {
        overlay: false,
      },
      proxy: {
        '/admin-api': {
          target: 'http://localhost/',
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(/^\/admin-api/, ''),
        },
        '/file-api': {
          // target: 'http://adminapi.h.wyix.top:86/',
          target: 'http://localhost/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/file-api/, ''),
        },
      },
    },
    plugins: createVitePlugins(env),
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css'],
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            // 自动添加前缀
            overrideBrowserslist: [
              'Android 4.1',
              'iOS 7.1',
              'Chrome > 31',
              'ff > 31',
              'ie >= 8',
              //'last 2 versions', // 所有主流浏览器最近2个版本
            ],
            grid: true,
          }),
        ],
      },
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/styles/vars.scss" as *;`,
          javascriptEnabled: true,
        },
      },
    },
    //打包配置
    esbuild: {
      pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
      drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined,
    },
    build: {
      minify: 'esbuild',
      outDir: env.VITE_OUT_DIR || 'dist',
      sourcemap: env.VITE_SOURCEMAP === 'true',
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      // brotliSize: false,
      rollupOptions: {
        plugins: env.VITE_USE_BUNDLE_ANALYZER === 'true' ? [visualizer()] : undefined,
        // 静态资源分类打包
        output: {
          manualChunks: {
            'vue-chunks': ['vue', 'vue-router', 'pinia'],
            'element-plus': ['element-plus'],
          },
        },
      },
      cssCodeSplit: !(env.VITE_USE_CSS_SPLIT === 'false'),
    },
    define: {
      'process.env': {},
    },
    optimizeDeps: {
      include,
      exclude,
    },
  }
})
